//
//  LS_NetworkTools.swift
//  weibo
//
//  Created by 罗李苏 on 16/5/23.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
//导入命名空间
import AFNetworking
//声明枚举
enum HTTPMethods: Int{
    
    case POST
    case GET
}
//声明结构体
struct API {
    
    static let hostName = "https://api.weibo.com/"
    //    static let hostName = "https://dev.api.weibo.com/"
    //加载用户token
    static let loadAccessToken = "oauth2/access_token"
    //加载用户信息
    static let loadUserInfo = "2/users/show.json"
    
    //加载首页数据
    static let loadHomedata = "2/statuses/home_timeline.json"
    
    //发布文本微博
    static let sendStatus = "2/statuses/update.json"
  
    //发布图片微博
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"

    
}

class LS_NetworkTools: AFHTTPSessionManager {
    
    //声明单例对象
    static let sharedTools: LS_NetworkTools = {
       
        //把url前面一样的部分 声明为基础的url地址
        let tools = LS_NetworkTools(baseURL:  NSURL(string: API.hostName))
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
        }()
        
    //MARK:封装get & post 请求
    func request(method: HTTPMethods, URLString: String, parameters: AnyObject, finished: (responseObject: AnyObject?, error: NSError?) -> ()){
        
        //定义闭包参数 将相同的闭包当做参数传递
        let success = {(task: NSURLSessionTask, result: AnyObject?) -> () in
        //执行请求成功的回调
            finished(responseObject: result, error: nil)
        }
        
        let failure = {(task: NSURLSessionTask?, error: NSError?) -> () in
            //执行请求成功的回调
            finished(responseObject: nil, error: error)
        }

        //MARK:根据不同的参数执行不同的请求
        if method == .GET {
            GET(URLString, parameters: parameters, progress: nil,success: success, failure: failure)
        }else{
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }

}

///MARK: 将用户认证 获取用户信息相关的方法归到这个分类里面
extension LS_NetworkTools{
    
    //请求用户的token
    func loadAccessToken(code: String, finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        let parameters = ["client_id" : client_id, "client_secret":client_secret, "grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        //调用封装的核心方法
        request(.POST, URLString: API.loadAccessToken, parameters: parameters, finished: finished)
    }
    
     //加载用户信息
        func loadUserInfo(response: [String : AnyObject],finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
            
            //用户访问接口权限的标识
            let token = response["access_token"]!
            let uid = response["uid"]!
            //字典中不可以添加 nil
            let parameters = ["access_token": token, "uid": uid]
            request(.GET, URLString: API.loadUserInfo, parameters: parameters, finished: finished)
        }
    

}

//MARK:首页相关
extension LS_NetworkTools{
    
    func loadHomePageData(since_id: Int64,max_id: Int64,finished: (responseObject: AnyObject?, error: NSError?) -> ()){
        
        guard let token = LS_UserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else{
        return
        }
//        let parameter = ["access_token" : token]
        var parameters = ["access_token" : token, "count" : "10"]
        
        if since_id > 0 {
            //把 since_id加到参数中
            parameters["since_id"] = "\(since_id)"
        }else{
            //把max_id加到参数中
            parameters["max_id"] = "\(max_id)"
        }
        
        request(.GET, URLString: API.loadHomedata, parameters: parameters, finished: finished)
    }
    
}
//MARK:发送文本微博
extension LS_NetworkTools {
    func sendStatus(status: String,images: [UIImage],finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = LS_UserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        
        let parameters = ["access_token": token,"status":status]
        if images.count > 0 {
            //图片微博  图片上传  AFN已经封装好AFN上传方法 使用POST方法
            self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formdata) in
                //将要上传的图片的二进制数据添加到formdata 中
                for image in images{
                    let imageData = UIImagePNGRepresentation(image)
                    formdata.appendPartWithFileData(imageData!, name: "pic", fileName: "lllll", mimeType: "application/octet-stream")
                }
                }, progress: nil, success: { (_, result) in
                    finished(responseObject: result, error: nil)
                }, failure: { (_, error) in
                    finished(responseObject: nil, error: error)
            })
        }else{
        
            request(.POST, URLString: API.sendStatus, parameters: parameters, finished: finished)
        }
    }
}
